<?php

namespace app\modules\config\controllers;

use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\SystemEvent;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use app\models\CustomTableViewSearch;
use app\models\CustomTableView;

use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use app\common\Functions;



class CustomController extends Controller
{
    
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}


    public function actionAutoattr($attr_spec_id=null)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $attrSpec = Functions::getAttrSpecValues($attr_spec_id);
        $out = ['results' => ['attr_spec_name' => $attrSpec->attr_spec_name, 'attr_spec_width' => $attrSpec->attr_spec_width, 'attr_field_name' => $attrSpec->attr_field_name]];
//        foreach($model as $value=>$name)
//        {
//            echo Html::tag('option',Html::encode($name),array('value'=>$value));
//        }
        Yii::trace("=====================              ============");
//        Yii::trace($attrSpec);
//        Yii::trace($out);

        return $out;

    }


    /***
     * @name   actionHide 字段的显示和隐藏
     * @description
     * @param
     * @return
     * @param null $id
     * @param null $last_url
     */
    public function actionHide($id=null,$last_url=null)
    {
        // 根据id查询结果
        $model = CustomTableView::find()->where(['id'=>$id])->one();

        // 如果显示结果是显示改为隐藏,否则改为显示
        $model->hide_flag = ($model->hide_flag==1) ? 0 : 1;
        $model->save();
        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);
    }

	/*
	 * 序列向上移动一个排位
	 *
	 * */
    public function actionUp($id=null,$last_url=null){

        // 取出本条记录的sort
        $model = CustomTableView::find()->where(['id'=>$id])->one();
        $sort = $model->sort;

        // 取出比本记录序列还小的记录中的max值
        $minModel = CustomTableView::find()->where(['<', 'sort', $model->sort])->orderBy('sort desc')->one();




        // 如果取出的记录结果是0 代表以及最小了，无需继续处理
        if ($minModel)
        {
            $minSort = $minModel->sort;

            // 如果有值，双方交换对应的sort

            //更改取出记录的sort为当前记录的sort
            $model->sort = $minSort;
            $model->save();

            //更改本记录的sort为上一记录的sort
            $minModel->sort = $sort;
            $minModel->save();
        }



        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);

    }

    /*
	 * 序列向下移动一个排位
	 *
	 * */
    public function actionDown($id=null,$last_url=null){
        // 取出本条记录的sort
        $model = CustomTableView::find()->where(['id'=>$id])->one();
        $sort = $model->sort;

        // 取出比本记录序列还大的记录中的max值
        $maxModel = CustomTableView::find()->where(['>', 'sort', $model->sort])->orderBy('sort ASC')->one();




        // 如果取出的记录结果是0 代表以及最小了，无需继续处理
        if ($maxModel)
        {
            $maxSort = $maxModel->sort;

            // 如果有值，双方交换对应的sort

            //更改取出记录的sort为当前记录的sort
            $model->sort = $maxSort;
            $model->save();

            //更改本记录的sort为上一记录的sort
            $maxModel->sort = $sort;
            $maxModel->save();
        }



        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);
    }

    /*
	 * 序列移动到顶端
	 *
	 * */
    public function actionTop($id=null,$last_url=null){

        // 取出本条记录的sort
        $model = CustomTableView::find()->where(['id'=>$id])->one();
        $sort = $model->sort;

        // 检查是否有比自己还要小的记录
        $minModel = CustomTableView::find()->where(['<', 'sort', $model->sort])->orderBy('sort desc')->one();




        // 如果取出的记录结果是0 代表以及最小了，无需继续处理
        if ($minModel) {

            // 将所有的记录+1,
            CustomTableView::updateAllCounters(['sort' => 1],['custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);

            // 将本记录设置为1
            $model->sort = 1;
            $model->save();
        }


        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);
    }

    /*
	 * 序列移动到底部
	 *
	 * */
    public function actionBottom($id=null,$last_url=null){

        // 取出本条记录的sort
        $model = CustomTableView::find()->where(['id'=>$id])->one();
        $sort = $model->sort;


        // 取出比本记录序列还大的记录中的max值
        $maxModel = CustomTableView::find()->where(['>', 'sort', $model->sort])->orderBy('sort desc')->one();




        // 如果取出的记录结果是0 代表以及最小了，无需继续处理
        if ($maxModel)
        {
            $maxSort = $maxModel->sort;

            // 将所有的记录-1,
            //CustomTableView::updateAllCounters(['sort' => -1],['custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);

            //更改取出记录的sort为当前记录的sort
            $model->sort = $maxSort+1;
            $model->save();




        }
        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);
    }

    /*
	 * 更新内容
	 *
	 * */
    public function actionUpdate($id=null,$last_url=null){


        // 初始化最重要的产品实例字段
        $postModel   = new CustomTableView();
        $model =  CustomTableView::find()->where(['id'=>$id])->one();




        if ($postModel->load(Yii::$app->request->post())
            && $postModel->validate() )
        {

            $postModel->create_date        = date("Y-m-d H:i:s",time());;
            $postModel->staff_id            = Yii::$app->user->id;


            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));


            $this->insertOrUpdateToTable($postModel,$model);

            if ($last_url)
            {
                return $this->redirect($last_url);
            }

            return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);

        }

        // 拥有的全部特性
        $attrSpecs         = Functions::getAttrSpecRelas($model->spec_id);
        $attrSpecsDownList = Functions::getAttrSpecDownList($attrSpecs);



        return $this->render('create',
            [
                'attrSpecs' => $attrSpecs,
                'attrSpecsDownList' => $attrSpecsDownList,
                'custom_name' => $model->custom_name,
                'spec_id' => $model->spec_id,
                'model' => $model
            ]);




    }




    /*
	 * 删除本条记录
	 *
	 * */
    public function actionDelete($id=null, $last_url=null){

        try{
            $this->delete($id);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
        }catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '删除失败.'));
            //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        if ($last_url)
        {
            return $this->redirect($last_url);
        }

        return $this->redirect(Yii::$app->request->referrer);
    }


     public function actionIndex($custom_name='order', $spec_id = '30001')
    {
        $searchModel = new CustomTableViewSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $custom_name, $spec_id);

        // 拥有的全部特性
        $attrSpecs         = Functions::getAttrSpecRelas($spec_id);
        $attrSpecsDownList = Functions::getAttrSpecDownList($attrSpecs);

         return $this->render('index',
             [
                 'spec_id' =>$spec_id,
                 'attrSpecs' => $attrSpecs,
                 'attrSpecsDownList' => $attrSpecsDownList,
                 'custom_name' => $custom_name,
                 'dataProvider' => $dataProvider,
                 'searchModel' =>  $searchModel]);
    }


    public function actionCreate($custom_name='order', $spec_id = '30001',$last_url=null)
    {

        $attrSpecs = [];
        $attrSpecsDownList = [];

        // 初始化类型
        $model = new CustomTableView();




        if ($model->load(Yii::$app->request->post())
            && $model->validate() )
        {

            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->staff_id   = Yii::$app->user->id;


            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToTable($model,null);

            if ($last_url)
            {
                return $this->redirect($last_url);
            }

            return $this->redirect(['/config/custom/index','custom_name' => $model->custom_name, 'spec_id' => $model->spec_id]);

        }

        // 拥有的全部特性
        $attrSpecs         = Functions::getAttrSpecRelas($spec_id);
        $attrSpecsDownList = Functions::getAttrSpecDownList($attrSpecs);

        $model->spec_id     = $spec_id;
        $model->custom_name = $custom_name;

        return $this->render('create',
            [
                'attrSpecs' => $attrSpecs,
                'attrSpecsDownList' => $attrSpecsDownList,
                'custom_name' => $custom_name,
                'spec_id' => $spec_id,
                'model' => $model
           ]);
    }

    public function insertOrUpdateToTable( $newModel, $oldModel=null, $orderAttrModel=null)
    {
        if($oldModel)
        {
            $model = CustomTableView::find()->where(['id'=>$newModel->id])->one();

            if ($model->custom_type!=1)
            {
                $model->sort                   = $newModel->sort;
                $model-> attr_spec_width     = $newModel->attr_spec_width;
                $model-> attr_spec_id         = $newModel->attr_spec_id;
                $model-> show_name            = $newModel->show_name ;
                $model->custom_type = 0;
            }
            else
            {
                $model->sort                   = $newModel->sort;
                $model-> attr_spec_width     = $newModel->attr_spec_width;
                $model-> attr_spec_id         = 0;
                $model-> show_name            = $newModel->show_name ;
                $model->custom_type = 1;
            }



            $model->save();




        }
        else
        {
            // 根据attr_spec_id获取对应的菜单名称
            $attrSpec = Functions::getAttrSpecRelaValues($newModel->spec_id,$newModel->attr_spec_id);
            $newModel->attr_field_name = $attrSpec->attrSpecs->attr_field_name;


            // 写死只能更新0的字段
            $newModel->custom_type = 0;
            $newModel->save();
        }
    }

    public function delete($id)
    {
        $customTableView = CustomTableView::find()->where(['id'=>$id])->one();
        if($customTableView)
        {
            $customTableView->delete();
        }
    }



}
